package com.fs.filter;

import com.fs.decorator.RewriteRequestDecorator;
import com.fs.decorator.RewriteResponseDecorator;
import com.fs.decorator.RewriteResponseDecoratorL;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
public class LogServiceFilter implements GatewayFilter, Ordered {

    public static String regexp = null;

    public LogServiceFilter(String regexp) {
        super();
        this.regexp = regexp;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        log.info("======>LogServiceFilter");
//        RewriteRequestDecorator rewriteRequestDecorator = new RewriteRequestDecorator(exchange.getRequest(), regexp);
//        // 构建新exchange
//        ServerWebExchange newExchange = exchange.mutate().request(rewriteRequestDecorator).build();
//        // 使用新exchange获取响应体
//        RewriteResponseDecorator rewriteResponseDecorator = new RewriteResponseDecorator(newExchange.getResponse());
//        newExchange = newExchange.mutate().response(rewriteResponseDecorator).build();
//        return chain.filter(newExchange);

        //获取路由路径
        String rawPath = exchange.getRequest().getURI().getRawPath();
        //获取需要转发的路径
        String newPath = rawPath.replaceAll(regexp, "/${segment}");
        //构建reques请求.添加一个请求头,删除旧的请求头Accpet，只接受json数据
        HttpHeaders.writableHttpHeaders(exchange.getRequest().getHeaders()).remove(HttpHeaders.ACCEPT);
        ServerHttpRequest request = exchange.getRequest().mutate().path(newPath).header("Accept", "application/json").build();
        //获取响应
        ServerHttpResponse response = exchange.getResponse();
        // 使用新exchange获取响应体
        RewriteResponseDecoratorL rewriteResponseDecorator = new RewriteResponseDecoratorL(response);
        //放行
        return chain.filter(exchange.mutate().request(request).response(rewriteResponseDecorator).build());
    }


    @Override
    public int getOrder() {
        return -100;
    }

}
